package com.millstein.baier.service.impl;

import cn.hutool.core.util.IdUtil;
import com.millstein.baier.exception.CustomerException;
import com.millstein.baier.mapper.QuestionRecordMapper;
import com.millstein.baier.model.dto.QuestionRecordDto;
import com.millstein.baier.model.entity.QuestionRecord;
import com.millstein.baier.service.UploadService;
import com.millstein.baier.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Value("${file.upload.location}")
    private String location;

    @Value("${file.server.prefix}")
    private String prefix;

    @Autowired
    private QuestionRecordMapper questionRecordMapper;

    /**
     * 上传图片并提交反馈
     * @param files 图片的数组
     * @param dto 问题提交的其他数据
     * @return
     */
    @Override
    @Transactional
    public void upload(List<MultipartFile> files, QuestionRecordDto dto) {
        if (CollectionUtils.isEmpty(files)) {
            throw new CustomerException("上传的图片不存在");
        }
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile multipartFile : files) {
            imageUrls.add(this.doUploadItem(multipartFile, dto));
        }
        List<QuestionRecord> list = new ArrayList<>();
        for (String imageUrl : imageUrls) {
            QuestionRecord record = new QuestionRecord(dto);
            record.setPictureurl(imageUrl);
            list.add(record);
        }
        int i = questionRecordMapper.batchInsertRecords(list);
        if (i != list.size()) {
            throw new CustomerException("保存出错记录时失败，请稍后再试");
        }
    }

    /**
     * 上传单个图片并保存反馈信息
     * @param multipartFile 图片信息
     * @param dto 问题提交的其他数据
     * @return
     */
    private String doUploadItem(MultipartFile multipartFile, QuestionRecordDto dto) {
        // 1.处理上传的文件命名
        String fileName = IdUtil.getSnowflake(1, 1).nextId() + ".jpg";

        // 2.进行目录打散，目录结构为`年月日/errid/文件名`
        String year = DateUtil.getCurrentYear();
        String month = DateUtil.getCurrentMonth();
        String day = DateUtil.getCurrentDay();
        String uploadDir = year + month + day + "/" + dto.getErrid();
        File dirFile = new File(location, uploadDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 3.创建目标文件
        File destFile = new File(dirFile, fileName);

        // 4.复制文件到服务器
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(destFile);
            IOUtils.copy(multipartFile.getInputStream(), outputStream);
            return prefix + uploadDir + "/" + destFile.getName();
        } catch (Exception e) {
            throw new CustomerException("保存文件时发生异常");
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
